<template>
  <div class="cart-container">
    <div>
      <!-- 滑动单元格 -->
      <van-swipe-cell v-for="item in cart" :key="item.id">
        <!-- 商品卡片 -->
        <van-card :title="item.goodsname" :price="item.price">
          <!-- 自定义数量区域 -->
          <div slot="num">
            <van-stepper
              :value="item.count"
              min="1"
              integer
              @change="
                (val) => {
                  countChanged(item.id, val)
                }
              "
            />
          </div>
          <!-- 自定义缩略图区域 -->
          <div slot="thumb">
            <van-checkbox checked-color="#FF4444" :value="item.status" @click="statusChanged(item.id, item.status)">
              <img :src="item.pic" alt="" class="thumb" />
            </van-checkbox>
          </div>
        </van-card>
        <!-- 滑动单元格右侧的删除按钮 -->
        <van-button slot="right" class="btn-remove" square type="danger" text="删除" @click="removeGoods(item.id)" />
      </van-swipe-cell>
    </div>

    <van-submit-bar :price="amount" button-text="提交订单">
      <van-checkbox checked-color="#FF4444" :value="isFullSelected" @click="changeAllState(!isFullSelected)">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters } from 'vuex'

export default {
  layout: 'cms',
  computed: {
    // 可以通过命名空间，简化映射的过程
    ...mapState('carts', {
      // 在映射 vuex 模块中状态的时候，必须使用函数进行映射
      cart: (state) => {
        return state.cart
      }
    }),
    ...mapGetters('carts', {
      amount: 'amount',
      isFullSelected: 'isFullSelected'
    })
  },
  methods: {
    ...mapMutations('carts', {
      updateCount: 'updateCount',
      updateStatus: 'updateStatus',
      remove: 'remove',
      changeAllState: 'changeAllState'
    }),
    // 数量发生了变化
    countChanged(id, count) {
      const goods = { id, count }
      this.updateCount(goods)
    },
    // 状态发生了变化
    statusChanged(id, status) {
      const goods = { id, status: !status }
      this.updateStatus(goods)
    },
    // 根据Id删除对应的商品
    removeGoods(id) {
      this.remove(id)
    }
  }
}
</script>

<style lang="less" scoped>
.cart-container {
  padding-bottom: 50px;
}
.van-card {
  margin: 0 !important;
  border-top: 1px solid #eee;
}
.van-card__content {
  justify-content: space-around;
}
.van-card__thumb {
  width: 120px;
}
.thumb {
  width: 90px;
  height: 90px;
}
.btn-remove {
  height: 100%;
  font-size: 12px;
}
.van-submit-bar {
  bottom: 50px;
  border-top: 1px solid #eee;
  padding-left: 15px;
}
</style>
